package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import pojo.User;

import dao.StoptimeHome;
import dao.UserHome;

import service.IMemberShipService;
import serviceImp.MembershipServiceImp;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final Logger _logger = Logger
		.getLogger(LoginServlet.class);
	
	private IMemberShipService memberShipServiceImp;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        MembershipServiceImp imp = new MembershipServiceImp();
        imp.setUserDAO(new UserHome());
        imp.setStoptimeDAO(new StoptimeHome());
        memberShipServiceImp = imp;
                
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		
		
		if (action.equals("logout")) {
		    request.getSession().removeAttribute("user");
		    response.sendRedirect("index.jsp");
		    
		    
		}else{
		    String username = request.getParameter("username");
			String password = request.getParameter("password");
			
			System.out.println("Received Login Request");
			System.out.println(username);
			System.out.println(password);
			
			if (username == null || password==null) {
			    
			    response.sendRedirect("index.jsp?error=username/password is null");
			}
			
			User user = memberShipServiceImp.login(username, password);
			
			if (user == null) {
			    //System.out.println("user not found");
			    response.sendRedirect("index.jsp?error=user not found");
			}else {
			    
			    System.out.println("Login success");
			    request.getSession().setAttribute("user", user);
			   
			
			    request.getRequestDispatcher("index.jsp").forward(request, response);
		
			}
		    
		    
		}
		
		
		
	}
}
